package top.porchwood.jweb.mcsm.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.sql.Timestamp;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author 一七年夏
 * @Link https://space.bilibili.com/16869954
 * @Email 2098833867@qq.com
 * @License GNU General Public Liscene 3.0
 * @DateTime 2021-08-02 17:37
 */
@Service
public class EmailService {
    private static EmailService emailService;
    private static final Logger logger = LogManager.getLogger();
    @Value("${spring.mail.username}")
    private String userName;

    public static EmailService getInstance() {
        return emailService;
    }
    @Autowired
    private JavaMailSender sender;
    @Autowired
    private JdbcTemplate jdbc;

    public EmailService() {
        emailService = this;
    }

    public void sendEmail(@NonNull String content, @NonNull String title, @NonNull String address) throws MessagingException {
        sendEmail(content, title, new String[]{address});
    }

    public void sendEmail(@NonNull String content, @NonNull String title, @NonNull String[] address) throws MessagingException {
        MimeMessage mm = sender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mm);
        message.setSubject(title);
        message.setFrom(userName);
        message.setTo(address);
        message.setSentDate(new Date());
        message.setText(content, true);
        sender.send(mm);
    }

    public boolean sendEmailAuthCode(@NonNull String address, @NonNull String userName) {
        try {
            String code = String.valueOf(Math.random()).substring(2, 8);
            sendEmail("""
                            <div style="max-width:1024px; margin: 0 auto;">
                                <p>
                                    【ChobitsMC】您的验证码为 <b style="text-decoration: underline;">%s</b> ，请保管好该验证码不要告诉其他人。<br />
                                    该验证码5分钟内有效
                                </p>
                                <br />
                                <p style="text-align: right;">系统自动发送，请不要回复</p>
                            </div>
                            """.formatted(code),
                    "【ChobitsMC】ChobitsMC游戏中心账号注册验证", address);
            jdbc.update("""
                    insert into cbmc_account_authcode(EMAIL, NAME, REQ_TIME, CODE) VALUES (?,?,?,?)
                    """, address, userName, new Timestamp(new Date().getTime()), code);
        } catch (Exception ex) {
            logger.error(ex);
            return false;
        }
        return true;
    }

}
